﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace FirmaTransportowa
{
    public partial class LoginForm : Form
    {
        SqlConnection dbConnection;
        public LoginForm()
        {
            InitializeComponent();
            SqlConnector connection = new SqlConnector();
            dbConnection = connection.getInstance();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool fieldsFilledOut = true;
            //walidacja formularza
            if (loginBox.Text.Trim() == String.Empty)
            {
                errorLogin.Text = "Podaj login";
                errorLogin.ForeColor = Color.DarkRed;
                login.ForeColor = Color.DarkRed;
                fieldsFilledOut = false;
            }
            if (passwordBox.Text.Trim() == String.Empty)
            {
                errorPassword.Text = "Podaj hasło";
                errorPassword.ForeColor = Color.DarkRed;
                password.ForeColor = Color.DarkRed;
                fieldsFilledOut = false;
            }

            //id roli zalogowanego użytkownika
            int userOccupationID = -1;

            //id użytkownika
            int userID = 0;

            if (fieldsFilledOut)
            {
                //sprawdzenie danych użytkownika
                SqlCommand selectUsers = new SqlCommand("SELECT * FROM Users", dbConnection);
                SqlDataReader userReader = null, workerReader;
                userReader = selectUsers.ExecuteReader();
                Boolean userFound = false;

                while (userReader.Read())
                {
                    if (userReader["login"].ToString() == loginBox.Text.Trim())
                    {
                        userFound = true;
                        //sprawdzenie hasła
                        if (userReader["password"].ToString() == passwordBox.Text.Trim())
                        {
                            userID = int.Parse(userReader["user_ID"].ToString());
                            //sprawdzenie roli zalogowanego użytkownika
                            SqlCommand selectLoggedWorker = new SqlCommand("SELECT * FROM Workers WHERE worker_ID = " + userReader["worker_ID"], dbConnection);
                            userReader.Close();
                            workerReader = selectLoggedWorker.ExecuteReader();
                            if (workerReader.Read())
                            {
                                userOccupationID = (int)workerReader["occupation_ID"];
                            }
                            workerReader.Close();
                            break;
                        }
                        else
                        {
                            errorPassword.Text = "Podane hasło jest nieprawidłowe";
                            errorPassword.ForeColor = Color.DarkRed;
                            password.ForeColor = Color.DarkRed;
                        }
                    }
                }

                if (!userFound) {
                    errorLogin.Text = "Użytkownik nie istnieje";
                    errorLogin.ForeColor = Color.DarkRed;
                    login.ForeColor = Color.DarkRed;
                }

                if( !userReader.IsClosed ) userReader.Close();

                if (userOccupationID >= 0)
                {
                    //wyświetlenie odpowiedniego okna (w zaleznosci od roli zalogowanego uzytkownika)
                    //identyfikatory ról zdefiniowane w tablicy Occupations
                    switch (userOccupationID) {
                        case 1: CashierPanel cashierPanel = new CashierPanel();
                                cashierPanel.Show();
                                break;
                        case 2: DispatcherPanel dispatcherPanel = new DispatcherPanel(userID);
                                dispatcherPanel.Show();
                                break;
                        case 3: StatisticsPanel statisticsPanel = new StatisticsPanel();
                                statisticsPanel.Show();
                                break;
                        case 4: DriverPanel driverPanel = new DriverPanel(userID);
                                driverPanel.Show();
                                break;
                        case 5: AdminPanel adminPanel = new AdminPanel();
                                adminPanel.Show();
                                break;
                    }
                    //zamkniecie polaczenia z baza danych
                    try
                    {
                        dbConnection.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }

                    //zamknięcie okna logowania
                    this.Hide();
                } 
            }

            
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            errorPassword.Text = String.Empty;
            password.ForeColor = Color.Black;
        }

        private void loginBox_TextChanged(object sender, EventArgs e)
        {
            errorLogin.Text = String.Empty;
            login.ForeColor = Color.Black;
        }

        private void recipientsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
       
        }

        private void recipientsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
      
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {
            try
            {
                dbConnection.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                Application.Exit();
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void loginBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(sender, e);
            }
        }

        private void passwordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(sender, e);
            }
        }
    }
}